import { Preferences } from '@capacitor/preferences';
import { create, StateCreator } from 'zustand';
import { subscribeWithSelector } from 'zustand/middleware';

export interface StoreConfig<T> {
  name: string;
  initialState: T;
  onRehydrate?: (state: T) => void;
}

export function createPersistedStore<T extends object>(
  config: StoreConfig<T>,
  stateCreator: StateCreator<T>
) {
  const { name, initialState, onRehydrate } = config;

  // Create the store with subscription support
  const useStore = create(
    subscribeWithSelector(
      (set, get) => ({
        ...initialState,
        ...stateCreator(set, get),
        
        // Add hydration methods
        hydrate: async () => {
          const stored = await Preferences.get({ key: name });
          if (stored.value) {
            const state = JSON.parse(stored.value);
            set(state);
            onRehydrate?.(state);
          }
        },
      })
    )
  );

  // Subscribe to changes and persist
  useStore.subscribe(
    (state) => state,
    async (state) => {
      await Preferences.set({
        key: name,
        value: JSON.stringify(state),
      });
    }
  );

  return useStore;
}